﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AnalyticsEngine.ClonesDetection;
using NClass.Core;
using NClass.DiagramEditor.ClassDiagram;
using NClass.DiagramEditor.ClassDiagram.Shapes;

namespace NClass.GUI.Dialogs
{
	public partial class SearchResults : Form
	{
		private ClonesDetectionEngine m_searcher = null;
		private List<DiagrammPartInfo> m_results = null;
		private int m_activeResult = 0;

		Diagram m_currentDiagram = null;
		List<Shape> m_selectedShapes = null;

		public SearchResults(ClonesDetectionEngine searcher)
		{
			InitializeComponent();
			m_searcher = searcher;
			if (Workspace.Default.ActiveProject.ItemCount > 0)
			{
				List<Diagram> d = new List<Diagram>();
				foreach (IProjectItem pi in Workspace.Default.ActiveProject.Items)
				{
					if (pi is Diagram)
					{
						d.Add(pi as Diagram);
					}
				}
				m_currentDiagram = d[0];

				m_selectedShapes = m_currentDiagram.GetSelectedShapes().ToList<Shape>();
			}

			if (m_searcher.Results.Count > 0)
			{
				m_results = m_searcher.Results[m_searcher.Processed[0]];
				m_labelTotalResultsCount.Text = m_results.Count.ToString();
				HighlightResult();
			}
			else
			{
				m_labelTotalResultsCount.Text = "0";
			}
			ValidateButtons();
		}

		private void m_prevResult_Click(object sender, EventArgs e)
		{
			--m_activeResult;
			HighlightResult();
			ValidateButtons();
		}

		private void m_nextResult_Click(object sender, EventArgs e)
		{
			++m_activeResult;
			HighlightResult();
			ValidateButtons();
		}

		private void label1_Click(object sender, EventArgs e)
		{

		}

		private void SearchResults_Load(object sender, EventArgs e)
		{
			
		}

		private void ValidateButtons()
		{
			if (m_searcher.Results.Count > 0)
			{
				m_prevResult.Enabled = m_activeResult > 0;
				m_nextResult.Enabled = m_activeResult < m_results.Count - 1; 
			}
			else
			{
				m_nextResult.Enabled = false;
				m_prevResult.Enabled = false;
			}
		}

		private void HighlightResult()
		{
			foreach (Shape s in m_selectedShapes)
			{
				s.IsSelected = false;
			}
			m_selectedShapes.Clear();
			for (int i = 0; i < m_currentDiagram.Shapes.Count<Shape>(); ++i)
			{
				Shape s = m_currentDiagram.Shapes.ToList<Shape>()[i];
				if (m_results[m_activeResult].Entities.Contains<IEntity>(s.Entity))
				{
					s.IsSelected = true;
					m_selectedShapes.Add(s);
				}
			}
			m_resultDetalies.Items.Clear();
			foreach (TypeBase tb in m_results[m_activeResult].Entities)
			{
				m_resultDetalies.Items.Add(tb.Name);
			}
			m_labelResultNumber.Text = (m_activeResult + 1).ToString();
		}

		private void m_resultDetalies_SelectedIndexChanged(object sender, EventArgs e)
		{

		}
	}
}
